package com.sv.jm.baselibrary.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sv.jm.baselibrary.R;
import com.sv.jm.baselibrary.event.EventAction;
import com.sv.jm.baselibrary.event.EventActionKey;
import com.sv.jm.baselibrary.utils.FastClickCheck;
import com.sv.jm.baselibrary.utils.LogHelper;
import com.sv.jm.baselibrary.utils.ScreenHelper;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by 胡金辉 on 2017/5/23.
 */

public abstract class BaseActivity extends FragmentActivity implements IBase, View.OnClickListener {
    View vsTop, vsLoading, vsContainer, vsError;
    ViewStub vs_top, vs_loading, vs_container, vs_error;

    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_layout);
        EventBus.getDefault().register(this);
        OnActivityCreated();
    }

    /**
     * 加载数据页面初始化
     */
    private void initStubLoding() {
        if (null == vsLoading) {
            vs_loading = findView(R.id.vs_loading);
            vsLoading = vs_loading.inflate();
        }
    }

    /**
     * 异常页面初始化
     */
    private void initStubError() {
        if (null == vsError) {
            vs_error = findView(R.id.vs_error);
            vsError = vs_error.inflate();
            LinearLayout errorLy = findView(vsError, R.id.errorLy);
            errorLy.setOnClickListener(this);
        }
    }

    /**
     * 显示加载页面
     *
     * @param msg 显示加载提示信息  为空使用默认设置
     */
    public void showLoading(String msg) {
        initStubLoding();
        TextView txtLoading = findView(vsLoading, R.id.txtLoading);
        if (!TextUtils.isEmpty(msg))
            txtLoading.setText(msg);
        vsLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏加载页面
     */
    public void hideLoading() {
        if (null != vsLoading)
            vsLoading.setVisibility(View.GONE);
    }

    /**
     * 显示异常页面
     *
     * @param msg 显示异常提示信息  为空使用默认设置
     */
    public void showError(String msg) {
        initStubError();
        TextView txtLoading = findView(vsError, R.id.txtError);
        if (!TextUtils.isEmpty(msg))
            txtLoading.setText(msg);
        vsError.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏异常页面
     */
    public void hideError() {
        if (null != vsError)
            vsError.setVisibility(View.GONE);
    }

    /**
     * 关闭软键盘
     *
     * @param view
     */
    public void closeKeyboard(View view) {
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 设置页面内容布局
     */
    public abstract int getContainerLayout();

    public void setContainerLayout() {
        if (null == vsContainer) {
            vs_container = findView(R.id.vs_container);
            int layoutId = getContainerLayout();
            if (layoutId > 0) {//正确获取布局文件id
                vs_container.setLayoutResource(getContainerLayout());
                vsContainer = vs_container.inflate();
            } else {
                LogHelper.logE(this, "layout_inflate_error  布局文件加载异常---请关注");
            }
        }
        OnCoustomLayoutCreated(vsContainer);
    }

    /**
     * 内容创建完成后，根据view查找相关组件
     *
     * @param v v为设置内容页面更目录view
     */
    public abstract void OnCoustomLayoutCreated(View v);

    /**
     * 初始化方法
     */
    public void OnActivityCreated() {
        setContainerLayout();
        setListeners();
        setDatas();
    }

    /**
     * top导航栏构造器
     *
     * @return
     */
    public TopBuilder showTop() {
        if (vsTop == null) {
            vs_top = findView(R.id.vs_top);
            vsTop = vs_top.inflate();
        }
        TopBuilder topBuilder = new TopBuilder(vsTop);
        return topBuilder;
    }

    public class TopBuilder {
        Button btnLeft, btnRight;
        ImageButton btnLeftImg, btnRightImg;
        TextView txtTitle;
        LinearLayout topLy;

        public TopBuilder(View v) {
            btnLeft = findView(v, R.id.btnLeft);
            btnRight = findView(v, R.id.btnRight);
            txtTitle = findView(v, R.id.txtTitle);
            btnLeftImg = findView(v, R.id.btnLeftImg);
            btnRightImg = findView(v, R.id.btnRightImg);
            topLy = findView(v, R.id.topLy);
            btnLeft.setOnClickListener(BaseActivity.this);
            btnRight.setOnClickListener(BaseActivity.this);
            btnLeftImg.setOnClickListener(BaseActivity.this);
            btnRightImg.setOnClickListener(BaseActivity.this);
        }

        /**
         * 设置title名称
         *
         * @param title
         * @return
         */
        public TopBuilder setTitle(String title) {
            txtTitle.setText(title);
            return this;
        }

        /**
         * 设置左侧top按钮文字
         *
         * @param leftButtonName
         * @return
         */
        public TopBuilder setLeftButton(String leftButtonName) {
            btnLeft.setText(leftButtonName);
            btnLeft.setVisibility(View.VISIBLE);
            btnLeftImg.setVisibility(View.GONE);
            return this;
        }

        /**
         * 设置左侧top按钮背景图片
         * 目前仅支持res
         *
         * @param leftButtonRes
         * @return
         */
        public TopBuilder setLeftButton(int leftButtonRes) {
            btnLeft.setText("");
            btnLeftImg.setImageResource(leftButtonRes);
            btnLeft.setVisibility(View.GONE);
            btnLeftImg.setVisibility(View.VISIBLE);
            return this;
        }

        /**
         * 设置右侧top按钮文字
         *
         * @param rightButtonName
         * @return
         */
        public TopBuilder setRightButton(String rightButtonName) {
            btnRight.setText(rightButtonName);
            btnRight.setVisibility(View.VISIBLE);
            btnRightImg.setVisibility(View.GONE);
            return this;
        }

        /**
         * 设置右侧top按钮背景图片
         * 目前仅支持res
         *
         * @param rightButtonRes
         * @return
         */
        public TopBuilder setRightButton(int rightButtonRes) {
            btnRight.setText("");
            btnRightImg.setImageResource(rightButtonRes);
            btnRight.setVisibility(View.GONE);
            btnRightImg.setVisibility(View.VISIBLE);
            return this;
        }

        public TopBuilder setTopBackGroundColor(int drawableRes) {
            topLy.setBackgroundResource(drawableRes);
            return this;
        }

        /**
         * weight作为调整title与两侧组件大小的控制参数
         * 说明 weight默认参数为1
         * 若存在两侧显示不完整的情况则适当调整中间title的长度达到适配的目的
         * 使用方法设置小于1的参数
         *
         * @param weight
         */
        public void setTitleWeight(float weight) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) txtTitle.getLayoutParams();
            if (null == layoutParams) {
                layoutParams = new LinearLayout.LayoutParams(getBaseContext(), null);
                layoutParams.width = 0;
                layoutParams.height = ScreenHelper.dp2px(getBaseContext(), 48);
            }
            layoutParams.weight = weight;
            txtTitle.setLayoutParams(layoutParams);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //快速查找组件
    public <T> T findView(int id) {
        return (T) findViewById(id);
    }

    public <T> T findView(View v, int id) {
        return (T) v.findViewById(id);
    }

    @Override
    public void onClick(View v) {
        int clickId = v.getId();
        if (FastClickCheck.isFaskClick())//误操作检测
            return;
        if (clickId == R.id.btnLeft||clickId == R.id.btnLeftImg) {//左侧按钮事件
            leftClick();
        } else if (clickId == R.id.btnRight||clickId == R.id.btnRightImg) {//右侧按钮事件
            rightClick();
        } else if (clickId == R.id.errorLy) {//异常页面点击刷新事件
            onErrorClick();
        } else {
            otherClick(v);
        }
    }

    /**
     * 异常页面点击事件
     */
    protected abstract void onErrorClick();

    /**
     * 左侧点击
     */
    public abstract void leftClick();

    /**
     * 右侧点击
     */
    public abstract void rightClick();

    /**
     * 其他点击
     */
    public abstract void otherClick(View v);

    //监听初始化
    @Override
    public void setListeners() {

    }

    //数据初始化
    @Override
    public void setDatas() {

    }

    /**
     * 退出程序事件
     *
     * @param eventAction
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void receiveAction(EventAction eventAction) {
        String action = eventAction.getAction();
        if (action.equals(EventActionKey.EXIT)) {
            finish();
        } else if (action.equals(EventActionKey.REFRESH)) {
            onRefreshData();
        } else {
            onOtherActionReceiver(eventAction);
        }
    }

    /**
     * 页面需要刷新的任务放在这里处理
     * 当发送刷新事件接受到后会自动执行刷新任务
     */
    protected abstract void onRefreshData();

    /**
     * 接受到其他总线通知时调用此方法做逻辑处理
     */
    public abstract void onOtherActionReceiver(EventAction eventAction);

    public void jumpActivity(Class<?> act) {
        startActivity(new Intent(this, act));
    }
}
